<template>
  <div class="shipping-address">
    <h1>收货地址管理</h1>
    <el-button type="primary" @click="showAddAddressDialog">添加收货地址</el-button>
    
    <el-table :data="addresses" border>
      <el-table-column prop="recipientName" label="收件人" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="address" label="地址" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="editAddress(scope.row)">编辑</el-button>
          <el-button type="danger" @click="deleteAddress(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="添加收货地址" :visible.sync="addAddressDialogVisible">
      <el-form :model="newAddress">
        <el-form-item label="收件人">
          <el-input v-model="newAddress.recipientName"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="newAddress.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="newAddress.address"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAddressDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAddress">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getShippingAddresses, addShippingAddress, updateShippingAddress, deleteShippingAddress } from '@/api/shippingAddress';

export default {
  data() {
    return {
      addresses: [],
      addAddressDialogVisible: false,
      newAddress: {
        recipientName: '',
        phone: '',
        address: '',
      },
    };
  },
  methods: {
    async fetchAddresses() {
      const userId = 1; // 假设用户ID为1，实际应从用户登录信息中获取
      const response = await getShippingAddresses(userId);
      this.addresses = response.data;
    },
    showAddAddressDialog() {
      this.addAddressDialogVisible = true;
      this.newAddress = { recipientName: '', phone: '', address: '' }; // 重置表单
    },
    async addAddress() {
      await addShippingAddress(this.newAddress);
      this.addAddressDialogVisible = false;
      this.fetchAddresses(); // 刷新地址列表
    },
    async deleteAddress(id) {
      await deleteShippingAddress(id);
      this.fetchAddresses(); // 刷新地址列表
    },
    editAddress(address) {
      // 编辑地址逻辑
      this.newAddress = { ...address }; // 填充表单
      this.addAddressDialogVisible = true; // 打开对话框
    },
  },
  mounted() {
    this.fetchAddresses(); // 初始加载地址
  },
};
</script>

<style scoped>
.shipping-address {
  padding: 20px;
}
</style> 